package com.icehand.utils.shortenurl;

import com.alibaba.fastjson.JSONArray;
import com.icehand.utils.config.SystemConstant;
import com.icehand.utils.constants.KeyConst;
import com.icehand.utils.constants.SinaApi;
import com.icehand.utils.okhttp.OkHttpUtils;
import org.apache.commons.lang3.StringUtils;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 新浪短链接生成
 * Created by icehand on 2017/5/10.
 */
public class SinaShortenUrl {
	private static final String source = SystemConstant.getConfig("sina.source");

	public static String getShortenUrl(String longUrl){
		String result = longUrl;
		if(StringUtils.isEmpty(longUrl)){
			return result;
		}

		Map<String,String> requestMap = new HashMap<>();
		requestMap.put(KeyConst.KEY_SOURCE,source);
		requestMap.put(KeyConst.KEY_URL_LONG, URLEncoder.encode(longUrl));
		String response = OkHttpUtils.get(SinaApi.SINA_SHORTEN,requestMap);

		if(response.startsWith("[")){
			JSONArray array = JSONArray.parseArray(response);
			result = array.getJSONObject(0).getString(KeyConst.KEY_URL_SHORT);
		}

		return result;
	}
}
